package lizhe.dummynode;

public class ReverseKGroup {
    public static ListNode reverseKGroup(ListNode head, int k) {

        ListNode dup = new ListNode(-1, head);
        ListNode tmp = head;

        int count = 0;
        while (tmp != null) {
            count++;
            tmp = tmp.next;
        }

        ListNode preGroup = dup;
        ListNode pre = null;
        ListNode cur = head;
        while (count >= k) {
            count -= k;

            ListNode tail = cur;
            for (int i = 0; i < k; i++) {
                ListNode next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }
            preGroup.next = pre;
            preGroup = tail;
            pre = null;
        }
        preGroup.next = cur;
        return dup.next;

    }

    private static ListNode reverse(ListNode head, ListNode newList, ListNode end) {

        if (newList == end)
            return newList;

        ListNode next = head.next;
        head.next = newList;
        return reverse(next, head, end);
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode list2 = new ListNode(2);
        ListNode list3 = new ListNode(3);
        ListNode list4 = new ListNode(4);
        ListNode list5 = new ListNode(5);
        ListNode list6 = new ListNode(6);
        ListNode list7 = new ListNode(7);
        ListNode list8 = new ListNode(8);

        head.next = list2;
        list2.next = list3;
        list3.next = list4;
        list4.next = list5;
        list5.next = list6;
        list6.next = list7;
        list7.next = list8;

        ListNode reverse = reverseKGroup(head, 3);
        System.out.println("");


    }
}
